-- 全民红包
--#include "data\config\activityconfig\DailyActivity\NationwideRedPacketsConfig.lua" once
--#include "data\functions\Common\RankMgr.lua" once                 --排行榜管理

--排行榜位置
NationwideRedActorName = 0   --玩家名字
NationwideRedDailyLastCount = 1  --剩余次数
NationwideRedHaveNotGetCount = 2  --抢到未领取的红包
NationwideRedGetGoldCount = 3  --抢到的红包
NationwideRedGetGoldCd = 4  --抢红包的cd
NationwideRedGetGoldIdx = 5  --抢红包的概率idx

--操作类型
NationwideRedOperationGive = 1      --赠送
NationwideRedOperationGet = 2       --抢红包

function NationwideRedPacketsStar(noTip)
    local dVar = System.getDyanmicVar()
    dVar.nationwideRedPacketsStart = System.getCurrMiniTime()
    if not noTip then
        System.broadcastTipmsg(Lang.ScriptTips.RedPacketsBroadCast016,ttScreenCenter + ttChatWindow)
    end
end

function NationwideRedPacketsEnd()
    local dVar = System.getDyanmicVar()
    dVar.nationwideRedPacketsStart = nil

    System.broadcastTipmsg(Lang.ScriptTips.RedPacketsBroadCast017,ttScreenCenter + ttChatWindow)
end

function IsNationwideRedPacketsStart()
    local dVar = System.getDyanmicVar()
    if dVar.nationwideRedPacketsStart and dVar.nationwideRedPacketsStart > 0 then
        return true
    end
    return NationwideRedPacketsCheckTime()
end


--记录并获取实际名次中间方法
function NationwideRedPackets(awards, myScore, awardCount)
    local idx
    local awardsIdx = 0
    for ii = 1, #awards do
        if not awardCount[ii] then
            awardCount[ii] = 0
        end
        if myScore >= awards[ii].needMinValue and awardCount[ii] < awards[ii].num then
            idx = awards[ii].firstRank  + awardCount[ii]
            awardsIdx = ii
            awardCount[ii] = awardCount[ii] + 1
            break
        end
    end
    return idx, awardsIdx, awardCount
end

--发送数据
function SendNationwideRedPacketsData(sysarg)
    local myBeforeIdx = 0
    local beforeScore = 0
    local myIdx = 0
    local myScore = 0
    local myLastCount = 0
    local needSearch = true
    local myCanGetGoldNum = 0
    local myCd = 0
    local myActorId = Actor.getActorId(sysarg)

    local sVar = System.getStaticVar()

    local npack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sNationwideRedPacketsData) 
    if not npack then return end
    local TotalRankNum = getNationwideRedPacketsNum()
    DataPack.writeByte(npack, TotalRankNum)
    local awardCount = {}
    local rankPtr = Ranking.getRanking(RankList[RANK_DEFINE_RED_PACKETS].strName)
    local iiindex = 1
    if rankPtr then
        local rankCount = Ranking.getRankItemCount(rankPtr)
        if rankCount > TotalRankNum then
            rankCount = TotalRankNum
        end
        if rankCount > 0 then
            for idx = 1, rankCount do
                local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
                if item then
                    local actorId = tonumber(Ranking.getId(item))
                    local score = Ranking.getPoint(item)    
                    if score >= NationwideRedPacketsConfig.awardNeedMinValue then
                        local newidx, awardsIdx, newAwardCount = NationwideRedPackets(NationwideRedPacketsConfig.RankAwards, score, awardCount)
                        if newidx then
                            awardCount = newAwardCount
                            DataPack.writeByte(npack, newidx)
                            DataPack.writeString(npack, Ranking.getSub(item, NationwideRedActorName))
                            DataPack.writeInt(npack, score)
                            if actorId == myActorId then
                                myIdx = newidx
                                myBeforeIdx = idx - 1
                                myScore = score
                                myLastCount = tonumber(Ranking.getSub(item, NationwideRedDailyLastCount)) or 0
                                myCanGetGoldNum = tonumber(Ranking.getSub(item, NationwideRedHaveNotGetCount)) or 0
                                myCd = tonumber(Ranking.getSub(item, NationwideRedGetGoldCd)) or 0
                                needSearch = false
                            end
                            iiindex = iiindex + 1
                        end
                    end
                end
            end
        end
    end
    if iiindex <= TotalRankNum then
        for ii = iiindex, TotalRankNum do
            DataPack.writeByte(npack, 0)
            DataPack.writeString(npack, "")
            DataPack.writeInt(npack, 0)
        end
    end

    if needSearch then
        local myItem = Ranking.getItemPtrFromId(rankPtr, myActorId)
        if myItem then
            myBeforeIdx = Ranking.getIndexFromPtr( myItem )
            myScore = Ranking.getPoint(myItem)   
            myLastCount = tonumber(Ranking.getSub(myItem, NationwideRedDailyLastCount)) or 0
            myCanGetGoldNum = tonumber(Ranking.getSub(myItem, NationwideRedHaveNotGetCount)) or 0
            myCd = tonumber(Ranking.getSub(myItem, NationwideRedGetGoldCd)) or 0
        end
    end

    DataPack.writeByte(npack, myIdx)
    DataPack.writeInt(npack, myScore)
    DataPack.writeByte(npack, myLastCount)
    DataPack.writeInt(npack, sVar.nationwideRedPacketsNum or NationwideRedPacketsConfig.systemGiveGoldNum)
    

    local dVar = Actor.getDyanmicVar(sysarg)
    local circle = dVar.record_red_packets_circle or 1
    local index = dVar.record_red_packets_index or 1

    local dataTable, curCicle, curIndex = getRecordGlobalTableData(RecordTableIndexDefine.NationwideRedPackets, circle, index, NationwideRedPacketsConfig.keepRecordCount)
    dVar.record_red_packets_circle =  curCicle
    dVar.record_red_packets_index =  curIndex
    if dataTable then
        local len = #dataTable
        --print("len ="..len)
        DataPack.writeByte(npack, len)
        for idx = 1, len do
            --print("idx = "..idx)
            DataPack.writeString(npack, dataTable[idx].param)
            DataPack.writeByte(npack, dataTable[idx].param1)
            DataPack.writeByte(npack, dataTable[idx].param2)
            DataPack.writeInt(npack, dataTable[idx].param3)
        end
    else
        --print("len = 0")
        DataPack.writeByte(npack, 0)
    end
    DataPack.writeInt(npack, myCanGetGoldNum)
    local lastCd = 0
    local curTime = System.getCurrMiniTime()
    if myCd >= curTime then
        lastCd = myCd - curTime
    end
    DataPack.writeShort(npack, lastCd)

    local limitCount = Ranking.getRankItemCountByLimit(rankPtr, NationwideRedPacketsConfig.awardNeedMinValue)
    if myBeforeIdx > limitCount then
        myBeforeIdx = limitCount
    end
    if myBeforeIdx > 0 then
        local beforeItem = Ranking.getItemFromIndex(rankPtr, myBeforeIdx - 1)    
        if beforeItem then
            beforeScore = Ranking.getPoint(beforeItem)   
        end
    end
    
    DataPack.writeInt(npack, beforeScore)
    
    DataPack.flush(npack) 
end

--捐赠红包
function NationwideRedPacketsGive(sysarg, packet)
    local num = DataPack.readInt(packet)
    NationwideRedPacketsGiveSub(sysarg, num)
end

--捐赠红包
function NationwideRedPacketsGiveSub(sysarg, num)
    if num < NationwideRedPacketsConfig.playerMinGiveGoldNum then
        Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.NationwideRedPackets001, NationwideRedPacketsConfig.playerMinGiveGoldNum), ttFlyTip)
        return
    end

    if Actor.getMoneyCount(sysarg, mtYuanbao) < num then
        Actor.sendItemLack( sysarg, qatYuanbao, 0, num )
        return
    end
    local myOldAwardsIdx, myOldIdx, myOldRankIdx = NationwideRedPacketsCalcRank(sysarg)
    if not Actor.delMoney( sysarg,mtYuanbao,num,LogIds.UpgradeGiftLogId,Lang.LogTips.UpgradeGift) then
        return
    end

    local sVar = System.getStaticVar()
    if not sVar.nationwideRedPacketsNum then
        sVar.nationwideRedPacketsNum = NationwideRedPacketsConfig.systemGiveGoldNum
    end
    sVar.nationwideRedPacketsNum = sVar.nationwideRedPacketsNum + num

    local actorId = Actor.getActorId(sysarg)
    gRankMgr_AddValue(actorId, RANK_DEFINE_RED_PACKETS, num)
    local myAwardsIdx, myIdx, myRankIdx  = NationwideRedPacketsCalcRank(sysarg)
    local myAwardIdx = NationwideRedPacketsCalcRank(sysarg)
    if (myOldRankIdx > 0 and myRankIdx > 0 and myOldAwardsIdx == myAwardsIdx) or (myRankIdx == 0 and myOldRankIdx == 0) then

    elseif myRankIdx == 0 and myOldRankIdx > 0 then
        NationwideRedPacketsClearAward(sysarg)
    else
        NationwideRedPacketsClearAward(sysarg)
        NationwideRedPacketsGiveAward(sysarg, myAwardsIdx)

        if myRankIdx > 0 then
            NationwideRedPacketsChangeAward(myRankIdx)
        end
    end

    Actor.triggerAchieveEvent(sysarg, 45, 4)

    System.broadcastTipmsg(string.format(Lang.ScriptTips.RedPacketsBroadCast011, Actor.getName(sysarg), num),ttScreenCenter + ttChatWindow)

    local saveData = {}
    saveData.param = Actor.getName(sysarg)
    saveData.param1 = NationwideRedOperationGive
    saveData.param2 = 0
    saveData.param3 = num
    setRecordGlobalTableData(RecordTableIndexDefine.NationwideRedPackets, saveData, NationwideRedPacketsConfig.keepRecordCount)

    SendNationwideRedPacketsData(sysarg)
end

--领红包
function NationwideRedPacketsAward(sysarg)
    local actorId = Actor.getActorId(sysarg)
    local vipLevel = Actor.getVipGrade(sysarg)
    local myCanGetGoldNum = gRankMgr_GetValueById(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedHaveNotGetCount) or 0
    local myGoldNum = gRankMgr_GetValueById(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldCount) or 0
    local myCfgIdx = gRankMgr_GetValueById(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldIdx) or 0
    local cfg = NationwideRedPacketsConfig.getGoldInfo[myCfgIdx]
    if not cfg then
        return
    end
    local myGetGoldNum
    if myCanGetGoldNum and myCanGetGoldNum > 0 then
        if vipLevel < NationwideRedPacketsConfig.getAwardNeedVipLevel then
            Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.NationwideRedPackets002, NationwideRedPacketsConfig.getAwardNeedVipLevel, myCanGetGoldNum), ttFlyTip)
            return 
        end
        local rewards = {{type = qatYuanbao, id = 0, count = myCanGetGoldNum}}
        GiveCommonAward(sysarg, rewards, LogIds.NationwideRedPacketsLogId, Lang.LogTips.NationwideRedPackets)

        gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedHaveNotGetCount, 0)

        local myCd = System.getCurrMiniTime() + NationwideRedPacketsConfig.getGoldCd
        gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldCd, myCd)
        myGetGoldNum = myCanGetGoldNum
    elseif myGoldNum and myGoldNum >0 then
        local rewards = {{type = qatYuanbao, id = 0, count = myGoldNum}}
        GiveCommonAward(sysarg, rewards, LogIds.NationwideRedPacketsLogId, Lang.LogTips.NationwideRedPackets)
        gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldCount, 0)
        myGetGoldNum = myGoldNum
    end

    if myGetGoldNum and myGetGoldNum > 0 then
        gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldIdx, 0)
            
        local myPrecent = cfg.getGoldPrecent*100
        if cfg.broadCast and cfg.broadCast ~= "" then
            System.broadcastTipmsg(string.format(cfg.broadCast, Actor.getName(sysarg), myGetGoldNum),ttScreenCenter + ttChatWindow)
        end
        local saveData = {}
        saveData.param = Actor.getName(sysarg)
        saveData.param1 = NationwideRedOperationGet
        saveData.param2 = myPrecent
        saveData.param3 = myGetGoldNum
        setRecordGlobalTableData(RecordTableIndexDefine.NationwideRedPackets, saveData, NationwideRedPacketsConfig.keepRecordCount)
    end
    SendNationwideRedPacketsData(sysarg)
end

--抢红包
function NationwideRedPacketsGet(sysarg)
    if not IsNationwideRedPacketsStart() then
        Actor.sendTipmsg(sysarg, Lang.ScriptTips.NationwideRedPackets005, ttFlyTip)
        return
    end
    local actorId = Actor.getActorId(sysarg)
    local vipLevel = Actor.getVipGrade(sysarg)
    local myCanGetGoldNum = gRankMgr_GetValueById(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedHaveNotGetCount) or 0
    local myGoldNum = gRankMgr_GetValueById(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldCount) or 0
    local myGoldCd = gRankMgr_GetValueById(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldCd) or 0
    
    if myCanGetGoldNum and myCanGetGoldNum > 0 then
        Actor.sendTipmsg(sysarg, Lang.ScriptTips.NationwideRedPackets007, ttFlyTip)
        return
    end
    if myGoldNum and myGoldNum > 0 then
        NationwideRedPacketsAward(sysarg)
    end
    local sVar = System.getStaticVar()
    if not sVar.nationwideRedPacketsNum then
        sVar.nationwideRedPacketsNum = NationwideRedPacketsConfig.systemGiveGoldNum
    end
    local lastCount = gRankMgr_GetValueById(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedDailyLastCount) or 0

    local myTotalCount = GetNationwideRedPacketsDailyTotalCount(sysarg)
    if lastCount and lastCount >= myTotalCount then
        Actor.sendTipmsg(sysarg, Lang.ScriptTips.NationwideRedPackets003, ttFlyTip)
        return 
    end

    if myGoldCd > System.getCurrMiniTime() then
        Actor.sendTipmsg(sysarg, Lang.ScriptTips.NationwideRedPackets006, ttFlyTip)
        return 
    end

    if sVar.nationwideRedPacketsNum and sVar.nationwideRedPacketsNum < NationwideRedPacketsConfig.canNotGetGoldSystemGoldNum then
        Actor.sendTipmsg(sysarg, Lang.ScriptTips.NationwideRedPackets004, ttFlyTip)
        return
    end

    lastCount = lastCount + 1
    gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedDailyLastCount, lastCount)
    local myGetGoldNum = 0
    local myRandNum = System.getRandomNumber(10000)
    for idx = 1, #NationwideRedPacketsConfig.getGoldInfo do
        local cfg = NationwideRedPacketsConfig.getGoldInfo[idx]
        if cfg.getGoldFactor >= myRandNum then
            myGetGoldNum = math.floor(cfg.getGoldPrecent * sVar.nationwideRedPacketsNum)
            if myGetGoldNum < NationwideRedPacketsConfig.canGetMinGoldNum then
                myGetGoldNum = NationwideRedPacketsConfig.canGetMinGoldNum
            end
            if myGetGoldNum > sVar.nationwideRedPacketsNum then
                myGetGoldNum = sVar.nationwideRedPacketsNum
            end
            sVar.nationwideRedPacketsNum = sVar.nationwideRedPacketsNum - myGetGoldNum
            gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldIdx, idx)
            local sendCd = 0
            if vipLevel < NationwideRedPacketsConfig.getAwardNeedVipLevel then
                gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedHaveNotGetCount, myGetGoldNum)
                Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.NationwideRedPackets002, NationwideRedPacketsConfig.getAwardNeedVipLevel, myGetGoldNum), ttFlyTip)
            else
                gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldCount, myGetGoldNum)
                local cd = System.getCurrMiniTime() + NationwideRedPacketsConfig.getGoldCd
                sendCd = NationwideRedPacketsConfig.getGoldCd
                gRankMgr_SetRankEx(actorId, RANK_DEFINE_RED_PACKETS, NationwideRedGetGoldCd, cd)
            end
            local npack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sNationwideRedPacketsAward) 
            if not npack then return end
            DataPack.writeInt(npack, sVar.nationwideRedPacketsNum)
            DataPack.writeByte(npack, lastCount)
            DataPack.writeInt(npack, myGetGoldNum)
            DataPack.writeShort(npack, sendCd)
            DataPack.flush(npack)
            break
        end
    end
end

--跨天
function NationwideRedPacketsCrossDay()
    local week = System.getDayOfWeek()
    if week == 1 then
        local awardCount = {}
        local rankPtr = Ranking.getRanking(RankList[RANK_DEFINE_RED_PACKETS].strName)
        if rankPtr then
            local rankCount = Ranking.getRankItemCount(rankPtr)
            if rankCount > 0 then
                for idx = 1, rankCount do
                    local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
                    if item then
                        local actorId = tonumber(Ranking.getId(item))
                        local score = Ranking.getPoint(item)    
                        if score >= NationwideRedPacketsConfig.awardNeedMinValue then
                            local player = Actor.getActorById(actorId)
                            if player then
                                NationwideRedPacketsClearAward(player)
                            end
                        else
                            break
                        end
                    end
                end
            end
        end

        gRankMgr_Clear(RANK_DEFINE_RED_PACKETS)

        local sVar = System.getStaticVar()
        if sVar.nationwideRedPacketsNum and sVar.nationwideRedPacketsNum == 0 then
            --sVar.nationwideRedPacketsNum = NationwideRedPacketsConfig.systemGiveGoldNum
        end 
    else
        local rankPtr = Ranking.getRanking(RankList[RANK_DEFINE_RED_PACKETS].strName)
        if rankPtr then
            local rankCount = Ranking.getRankItemCount(rankPtr)
            if rankCount > 0 then
                for idx = 1, rankCount do
                    local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
                    if item then
                        Ranking.setSub(item, NationwideRedDailyLastCount, 0)
                    end
                end
            end
        end
    end
end

function NationwideRedPacketsNewVersionFirstClear()
    local sVar = System.getStaticVar()
    if sVar.nationwideRedPacketsNewVersion then
        return
    end
    sVar.nationwideRedPacketsNewVersion = 1
    if not sVar.nationwideRedPacketsNum then
        sVar.nationwideRedPacketsNum = NationwideRedPacketsConfig.systemGiveGoldNum
    elseif sVar.nationwideRedPacketsNum < NationwideRedPacketsConfig.systemGiveGoldNum then
        sVar.nationwideRedPacketsNum = NationwideRedPacketsConfig.systemGiveGoldNum
    end
    local rankPtr = Ranking.getRanking(RankList[RANK_DEFINE_RED_PACKETS].strName)
    if rankPtr then
        local rankCount = Ranking.getRankItemCount(rankPtr)
        if rankCount > 0 then
            for idx = 1, rankCount do
                local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
                if item then
                    Ranking.setSub(item, NationwideRedDailyLastCount, 0)
                    Ranking.setSub(item, NationwideRedHaveNotGetCount, 0)
                    Ranking.setSub(item, NationwideRedGetGoldCount, 0)
                    Ranking.setSub(item, NationwideRedGetGoldCd, 0)
                    Ranking.setSub(item, NationwideRedGetGoldIdx, 0)
                end
            end
        end
    end
end

--清除奖励和buff
function NationwideRedPacketsClearAward(sysarg)
    local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
    if NationwideRedPacketsConfig.awardMinBuffList then
        for ii = 1, #NationwideRedPacketsConfig.awardMinBuffList[vocation] do
            local buffId = NationwideRedPacketsConfig.awardMinBuffList[vocation][ii]
            if Actor.hasBuffById(sysarg, buffId) then
                Actor.delBuffById(sysarg, buffId)
            end
        end
    end

    if NationwideRedPacketsConfig.awardMinTitleId then
        local titleId = NationwideRedPacketsConfig.awardMinTitleId
        if Actor.hasTopTitle(sysarg, titleId) then
            Actor.delTopTitle(sysarg, titleId)
        end
    end
    
    for idx = 1, #NationwideRedPacketsConfig.RankAwards do
        local cfg = NationwideRedPacketsConfig.RankAwards[idx]
        if cfg.awardBuffList then
            for ii = 1, #cfg.awardBuffList[vocation] do
                local buffId = cfg.awardBuffList[vocation][ii]
                if Actor.hasBuffById(sysarg, buffId) then
                    Actor.delBuffById(sysarg, buffId)
                end
            end
        end

        if cfg.awardTitleId then
            local titleId = cfg.awardTitleId
            if Actor.hasTopTitle(sysarg, titleId) then
                Actor.delTopTitle(sysarg, titleId)
            end
        end
    end
end

--获取奖励
function NationwideRedPacketsGiveAward(sysarg, myAwardIdx)
    if myAwardIdx then
        local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
        if myAwardIdx > 0 and NationwideRedPacketsConfig.RankAwards[myAwardIdx] then
            local myAwardConfig = NationwideRedPacketsConfig.RankAwards[myAwardIdx]
            if myAwardConfig.awardBuffList then
                for ii = 1, #myAwardConfig.awardBuffList[vocation] do
                    local buffId = myAwardConfig.awardBuffList[vocation][ii]
                    if not Actor.hasBuffById(sysarg, buffId) then
                        Actor.addBuffById(sysarg, buffId)
                    end
                end
            end
            if myAwardConfig.awardTitleId then
                local titleId = myAwardConfig.awardTitleId
                if not Actor.hasTopTitle(sysarg, titleId) then
                    Actor.addTopTitle(sysarg, titleId)
                end
            end
        else
            if NationwideRedPacketsConfig.awardMinBuffList then
                for ii = 1, #NationwideRedPacketsConfig.awardMinBuffList[vocation] do
                    local buffId = NationwideRedPacketsConfig.awardMinBuffList[vocation][ii]
                    if not Actor.hasBuffById(sysarg, buffId) then
                        Actor.addBuffById(sysarg, buffId)
                    end
                end
            end

            if NationwideRedPacketsConfig.awardMinTitleId then
                local titleId = NationwideRedPacketsConfig.awardMinTitleId
                if not Actor.hasTopTitle(sysarg, titleId) then
                    Actor.addTopTitle(sysarg, titleId)
                end
            end
        end
    end 
end

--计算玩家当前排行
function NationwideRedPacketsCalcRank(sysarg)
    local myIdx = 0
    local myAwardIdx = 0
    local rankIdx = 0
    local myRankIdx = 0
    local myScore = 0
    local rankPtr = Ranking.getRanking(RankList[RANK_DEFINE_RED_PACKETS].strName)
    if rankPtr then
        local TotalRankNum = getNationwideRedPacketsNum()
        local actorid = Actor.getActorId(sysarg)
        local myItem = Ranking.getItemPtrFromId(rankPtr, actorid)
        if myItem then
            rankIdx = Ranking.getIndexFromPtr( myItem ) + 1
            myRankIdx = rankIdx
            myScore = Ranking.getPoint(myItem)  
            if myScore < NationwideRedPacketsConfig.awardNeedMinValue then
                myIdx = 0
                myRankIdx = 0
            else
                if rankIdx == 1 then
                    for ii = 1, #NationwideRedPacketsConfig.RankAwards do
                        if myScore >= NationwideRedPacketsConfig.RankAwards[ii].needMinValue then
                            myIdx = NationwideRedPacketsConfig.RankAwards[ii].firstRank 
                            myAwardIdx = ii
                            break
                        end
                    end
                else
                    local awardCount = {}
                    if rankIdx > TotalRankNum then
                        myIdx = 0
                    else
                        for idx = 1, rankIdx - 1 do
                            local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
                            if item then
                                local score = Ranking.getPoint(item) 
                                if score >= NationwideRedPacketsConfig.awardNeedMinValue then
                                    for ii = 1, #NationwideRedPacketsConfig.RankAwards do
                                        if score >= NationwideRedPacketsConfig.RankAwards[ii].needMinValue then
                                            if not awardCount[ii] then
                                                awardCount[ii] = 1
                                                break
                                            elseif awardCount[ii] >= NationwideRedPacketsConfig.RankAwards[ii].num then

                                            else
                                                awardCount[ii] = awardCount[ii] + 1
                                                break
                                            end
                                        end
                                    end
                                end
                            end
                        end
                        for ii = 1, #NationwideRedPacketsConfig.RankAwards do
                            if not awardCount[ii] then
                                awardCount[ii] = 0
                            end
                            if myScore >= NationwideRedPacketsConfig.RankAwards[ii].needMinValue and awardCount[ii] < NationwideRedPacketsConfig.RankAwards[ii].num then
                                myIdx = NationwideRedPacketsConfig.RankAwards[ii].firstRank  + (awardCount[ii] or 0)
                                myAwardIdx = ii
                                break
                            end
                        end
                    end
                end
            end
        end
    end
    return myAwardIdx, myIdx, myRankIdx
end

--玩家登陆
function NationwideRedPacketsLogin(sysarg)
    NationwideRedPacketsClearAward(sysarg)
    local myAwardIdx, myIdx, myRankIdx = NationwideRedPacketsCalcRank(sysarg)
    if myRankIdx == 0 then
        return
    end
    NationwideRedPacketsGiveAward(sysarg, myAwardIdx)
end

--计算总共上榜人数
function getNationwideRedPacketsNum()
    local num = 0
    for idx = 1 , #NationwideRedPacketsConfig.RankAwards do
        num = num + NationwideRedPacketsConfig.RankAwards[idx].num
    end
    return num
end

function NationwideRedPacketsChangeAward(myRankIdx)
    local TotalRankNum = getNationwideRedPacketsNum()

    local awardCount = {}
    local rankPtr = Ranking.getRanking(RankList[RANK_DEFINE_RED_PACKETS].strName)
    if rankPtr then
        local rankCount = Ranking.getRankItemCount(rankPtr)
        if rankCount > TotalRankNum + 1 then
            rankCount = TotalRankNum + 1
        end
        if rankCount > 0 and rankCount > myRankIdx then
            for idx = 1, rankCount do
                local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
                if item then
                    local actorId = tonumber(Ranking.getId(item))
                    local score = Ranking.getPoint(item)    
                    if score >= NationwideRedPacketsConfig.awardNeedMinValue then
                        local newidx, awardsIdx, newAwardCount = NationwideRedPackets(NationwideRedPacketsConfig.RankAwards, score, awardCount)
                        local player = Actor.getActorById(actorId)
                        if player and idx > myRankIdx then
                            NationwideRedPacketsClearAward(player)
                            NationwideRedPacketsGiveAward(player, awardsIdx)
                        end
                    end
                end
            end
        end
    end
end


function NationwideRedPacketsVipChange(sysarg, oldVipGrade, newVipGrade)
    if not oldVipGrade or not newVipGrade then
        return
    end
    if oldVipGrade >= newVipGrade then
        return
    end
    local sVar = System.getStaticVar()
    if not sVar.nationwideRedPacketsNum then
        sVar.nationwideRedPacketsNum = NationwideRedPacketsConfig.systemGiveGoldNum
    end 
    for idx = oldVipGrade + 1, newVipGrade do
        for ii = 1, #NationwideRedPacketsConfig.vipSystemPutGoldNum do
            local cfg = NationwideRedPacketsConfig.vipSystemPutGoldNum[ii]
            if cfg.vipLevel == idx then
                sVar.nationwideRedPacketsNum = sVar.nationwideRedPacketsNum + cfg.goldNum
                if cfg.broadCast and cfg.broadCast ~= "" then
                    System.broadcastTipmsg(string.format(cfg.broadCast, Actor.getName(sysarg), cfg.goldNum),ttScreenCenter + ttChatWindow)
                end
                break
            end
        end
    end
end

function NationwideRedPacketsDmkjHandle(sysarg, count)
    if not count or count <= 0 then
        return
    end
    local sVar = System.getStaticVar()
    if not sVar.nationwideRedPacketsNum then
        sVar.nationwideRedPacketsNum = NationwideRedPacketsConfig.systemGiveGoldNum
    end 
    for ii = 1, #NationwideRedPacketsConfig.dmkjSystemPutGoldNum do
        local cfg = NationwideRedPacketsConfig.dmkjSystemPutGoldNum[ii]
        if cfg.count == count then
            sVar.nationwideRedPacketsNum = sVar.nationwideRedPacketsNum + cfg.goldNum
            if cfg.broadCast and cfg.broadCast ~= "" then
                System.broadcastTipmsg(string.format(cfg.broadCast, Actor.getName(sysarg), cfg.goldNum),ttScreenCenter + ttChatWindow)
            end
            break
        end
    end
end

function GetNationwideRedPacketsDailyTotalCount(sysarg)
    local vipLevel = Actor.getVipGrade(sysarg)
    for idx = 1, #NationwideRedPacketsConfig.dailyGetAwardCount do
        local cfg = NationwideRedPacketsConfig.dailyGetAwardCount[idx]
        if cfg.vipLevel == vipLevel then
            return cfg.dailyCount
        end
    end
    return 0
end

--检查开启
function NationwideRedPacketsCheckTime()
    for i,v in ipairs(NationwideRedPacketsConfig.getRedPacketsTime) do
        if System.isInTimeRange(v[1][1], v[1][2], 0, v[2][1], v[2][2], 0) then
            NationwideRedPacketsStar(true)
            return true
        end 
    end
    return false
end
